package com.meteor.downloader.videodownloader.ui

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.meteor.downloader.videodownloader.R
import kotlin.math.min

class CircleRingView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
    private val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        color = ContextCompat.getColor(context, R.color.mdm_0C0900_50)
        strokeWidth = 10f
        strokeCap = Paint.Cap.ROUND
    }

    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        color = ContextCompat.getColor(context, R.color.mdm_0C0900)
        strokeWidth = 10f
        strokeCap = Paint.Cap.ROUND
    }

    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.BLACK
        textSize = 24f
        textAlign = Paint.Align.CENTER
        typeface = Typeface.DEFAULT_BOLD
    }

    private var progress = 0f // 0~100

    fun setProgress(percent: Float) {
        progress = percent.coerceIn(0f, 100f)
        invalidate()
    }

    private val mOval = RectF()

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val radius = min(width, height) / 2f - progressPaint.strokeWidth
        val centerX = width / 2f
        val centerY = height / 2f

        mOval.left = centerX - radius
        mOval.top = centerY - radius
        mOval.right = centerX + radius
        mOval.bottom = centerY + radius

        // 绘制背景圆环
        canvas.drawArc(mOval, 0f, 360f, false, bgPaint)

        // 绘制进度圆环（从 -90° 位置开始）
        val sweepAngle = progress / 100f * 360f
        canvas.drawArc(mOval, -90f, sweepAngle, false, progressPaint)

        // 绘制百分比文字
        val text = "${progress.toInt()}%"
        val fontMetrics = textPaint.fontMetrics
        val textHeight = (fontMetrics.descent + fontMetrics.ascent) / 2
        canvas.drawText(text, centerX, centerY - textHeight, textPaint)
    }
}